﻿using Process.Domain.DTO.OutDTO;
using Process.Domain.Entities;
using Process.Infrastructure.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Services;

namespace Process.Domain.Steps
{
    public class AuditStep : StepBody
    {
        public readonly IWorkflowRegistry workflowRegistry;
        public readonly IProcessRepository<ProcessAuditModel> _processautiModel;
        public AuditStep(IWorkflowRegistry workflowRegistry, IProcessRepository<ProcessAuditModel> processautiModel)
        {
            this.workflowRegistry = workflowRegistry;
            _processautiModel = processautiModel;
        }
        public long UserAuditId { get; set; }
        public string UserAuditName { get; set; }
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            if (!context.ExecutionPointer.EventPublished)
            {
                _processautiModel.Create(new ProcessAuditModel
                {
                    Id = GenerateSnowflakeId(),
                    WorkflowId = context.Workflow.Id,
                    StepId = context.Step.ExternalId,
                    StepName = context.Step.Name,
                    CreatedAt = DateTime.Now,
                    AuditUserId = UserAuditId,
                    AuditUserName = UserAuditName,
                    AuditType = "审核中", 
                    Status = "审核中"
                });
                Console.WriteLine($"等待{UserAuditName}审批中，该步骤是{context.Step.Name}");
                return ExecutionResult.WaitForEvent("MyEvent", context.Workflow.Id, DateTime.Now);

            }
            var def = workflowRegistry.GetDefinition(context.Workflow.WorkflowDefinitionId, context.Workflow.Version);

            var EnventData = context.ExecutionPointer.EventData as AuditprocessDTO;

            Console.WriteLine($"{UserAuditName}审批类型:{EnventData.Remark}");
            return ExecutionResult.Next();

        }

        private long GenerateSnowflakeId()
        {
            // 简化版雪花ID实现
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            long machineId = 1; // 机器ID
            long sequence = new Random().Next(0, 4095); // 序列号

            return ((timestamp - 1288834974657L) << 22) | (machineId << 12) | sequence;
        }
    }
}
